import {errorResponse } from "../helpers";
import jwt from "jsonwebtoken";
export function auth(req, res, next) {
  const authHeader = req.headers["authorization"];
  if (!authHeader) {
    return errorResponse(res, 401, 1, "缺少 Authorization 头");
  }
  // 判断是否是 Bearer 格式
  const parts = authHeader.split(" ");
  if (parts.length !== 2 || parts[0] !== "Bearer") {
    return errorResponse(res, 401, 1, "Authorization 格式错误");
  }
  const token = parts[1];
  const secretKey = Meteor.settings?.private?.jwtSecret || "defaultSecret";
  // 校验 token
  try {
    req.userInfo = jwt.verify(token, secretKey);
    next();
  } catch (err) {
    return errorResponse(res, 401, 1, "Token无效或已过期: " + err.message);
  }
}
